package com.coder.rental.security;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

/**
 * Spring Security配置类:整合处理器
 */
@Configuration
@EnableWebSecurity
public class SecurityConfig {

    @Autowired
    private LoginSuccessHandler loginSuccessHandler;//成功处理器
    @Autowired
    private LoginFailureHandler loginFailureHandler;//失败处理器
    @Autowired
    private CustomerAccessDeniedHandler customerAccessDeniedHandler;//无权访问
    @Autowired
    private CustomerAnonymousEntryPointHandler customerAnonymousEntryPointHandler;//匿名用户无权访问
    @Autowired
    private CustomerUserDetailService customerUserDetailService;
    @Autowired
    private VerifyTokenFilter verifyTokenFilter;

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity httpSecurity)throws Exception{
        //登录前过滤:
        //TODOtoken还没做出来
        httpSecurity.addFilterBefore(verifyTokenFilter, UsernamePasswordAuthenticationFilter.class);
        //登录过程处理
        httpSecurity.formLogin().loginProcessingUrl("/rental/user/login")
                .successHandler(loginSuccessHandler)
                .failureHandler(loginFailureHandler)
                .and()
                .sessionManagement()
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                .authorizeHttpRequests()
                .requestMatchers("rental/user/login")
                .permitAll()
                .anyRequest().authenticated()
                .and()
                .exceptionHandling()
                .authenticationEntryPoint(customerAnonymousEntryPointHandler)
                .accessDeniedHandler(customerAccessDeniedHandler)
                .and()
                .cors()
                .and()
                .csrf().disable()
                .userDetailsService(customerUserDetailService);

        return httpSecurity.build();
    }










}
